package com.beeasy.hzbpm.ctrl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.beeasy.hzbpm.filter.Auth;
import com.github.llyb120.nami.core.MultipartFile;
import com.github.llyb120.nami.core.RestException;
import com.github.llyb120.nami.ctrl.Ctrl;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.Json;
import com.github.llyb120.json.Obj;
import com.mongodb.client.MongoCollection;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.beetl.sql.core.SQLReady;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.beeasy.hzbpm.bean.MongoService.db;
import static com.github.llyb120.json.Json.*;

/**
 * @Author: Stunievi
 * @Date: 2019/12/27 10:24
 */
public class user extends Ctrl {
    private MongoCollection<Document> userdb = db.getCollection("user");
    static String tempDir = System.getProperty("java.io.tmpdir");
    public Object index(){
//        System.err.println(ObjectId.get());
        return o("sda",213);
    }

    public Object list(){
        int i = $get.i("page", 1);
        int size = $get.i("size", 10);
        String key = $get.s("key", "");
        Obj $match = o();
        if(!key.isEmpty()){
            $match.putAll(o(
                    "$or", a(
                            o("username", o("$regex", key )),
                            o("true_name", o("$regex", key ))
                    )
            ));
        }
        long count = userdb
                .count($match.toBson());
        Arr list = a();
        if(count > 0){
            list = userdb
                    .aggregate(a(
                            o("$match", $match),
                            o("$project", o(
                                    "uid", "$id",
                                    "name", o("$concat", a("$true_name", "(", "$username", ")"))
                            )),
                            o("$skip", (i - 1) * size),
                            o("$limit", size)
                    ).toBson())
                    .into(a());
        }
        return o(
                "total", count,
                "list", list
        );
    }

    /**
     * 部门人员列表
     * d_name: "党建办公室"
     * name: "基础角色"
     * */
    public Object getUser(){
        int page = $get.i("page", 1);
        int size = $get.i("size", 10);
        int lastPage = page * size;
        page = (page - 1) * size;
        Obj condition = o("$match",o("orgs",o("$elemMatch",
                o("$and",a(
                        o("id",$get.s("id")),
                        o("type",o("$in",a(
                                "DEP",
                                "ROLE"
                        )))
                ))
        )));
        Arr users = db.getCollection("user").aggregate(
                a(
                        condition,
                        o("$project",o("id","$id","username","$username","phone","$phone","true_name","$true_name","orgs","$orgs")),
                        o("$skip",page),
                        o("$limit",10)
                ).toBson()
        ).into(a());
        Arr count = db.getCollection("user").aggregate(
                a(
                        condition,
                        o("$project",o("id","$id")),
                        o("$count","count")
                ).toBson()
        ).into(a());
        // 获取所有用户的orgs
        Arr orgs = a();
        for(Object i : users){
            Map data = (Map)i;
//            System.err.println(data.get("orgs"));
            ArrayList org = (ArrayList)data.get("orgs");
            for(Object t : org){
                orgs.add(((Map)t).get("id"));
            }
        }
//        System.err.println(count.size());
        // 根据orgs查询org
        Arr allUser = userOparetion(users,orgs);
        if(count.size() != 0){
            return o("data",allUser,"totalRow",Integer.parseInt(count.o(0).s("count") ));

        }else{
            return o("data",null,"totalRow",0);
        }
    }
    /**
     * 部门下级所有人员
     * */
    public Object getUsers(){
        int page = $get.i("page", 1);
        int size = $get.i("size", 10);
        page = (page - 1) * size;
        Arr dep = db.getCollection("dep").aggregate(
                a(
                        o("$match",o("id",$get.s("id"))),
                        o("$graphLookup",o("from","dep","startWith","$id","connectFromField","id","connectToField","pid","as","dep"))
                ).toBson()
        ).into(a());
//        System.err.println(dep);
        Arr depList = a();
        depList.add(((Map)dep.get(0)).get("id"));
        ArrayList underDep = (ArrayList)((Map)dep.get(0)).get("dep");
        if(underDep != null){
            for(Object i : underDep){
//                Map mp = (Map)i;
//                System.err.println(((Map) i).get("id"));
                depList.add(((Map) i).get("id"));
            }
        }
        Obj condition = o("$match",o("orgs",o("$elemMatch",
                o("$and",a(
                        o("id",o("$in",depList)),
                        o("type",o("$in",a(
                                "DEP",
                                "ROLE"
                        )))
                ))
        )));
        Arr users = db.getCollection("user").aggregate(
                a(
                        condition,
                        o("$project",o("id","$id","username","$username","phone","$phone","true_name","$true_name","orgs","$orgs")),
                        o("$skip",page),
                        o("$limit",10)
                ).toBson()
        ).into(a());
        Arr count = db.getCollection("user").aggregate(
                a(
                        condition,
                        o("$project",o("id","$id")),
                        o("$count","count")
                ).toBson()
        ).into(a());
        // 获取所有用户的orgs
        Arr orgs = a();
        for(Object i : users){
            Map data = (Map)i;
//            System.err.println(data.get("orgs"));
            ArrayList org = (ArrayList)data.get("orgs");
            for(Object t : org){
                orgs.add(((Map)t).get("id"));
            }
        }
//        System.err.println(orgs);
        // 根据orgs查询org
        Arr allUser = userOparetion(users,orgs);
        if(count.size() == 0){
            return o("data",allUser,"totalRow",0);

        }
        return o("data",allUser,"totalRow",Integer.parseInt(count.o(0).s("count") ));
    }
    /**
     * 用户编辑页详情
     *
     * */
    public Object getUserInfo(){
        Arr data = db.getCollection("user").aggregate(
                a(
                        o("$match",o("id",$get.s("id"))),
                        o("$project",o("id","$id","username","$username","user_code","$user_code","sex","$sex","phone","$phone","true_name","$true_name","orgs","$orgs"))
                ).toBson()
        ).into(a());
//                .group(e->(((Document)e).get("id")));
        ArrayList org = (ArrayList)((Map)(data.get(0))).get("orgs") == null ? new ArrayList() : (ArrayList)((Map)(data.get(0))).get("orgs");
        StringBuilder oids = new StringBuilder("");
        StringBuilder dids = new StringBuilder("");
        if(org.size() != 0){
            for(Object i : org){
                Map li = (Map)i;
                if(li.get("type").equals("ROLE")){
                    if(oids.length() == 0){
                        oids.append(li.get("id"));
                    }else{
                        oids.append("," + li.get("id"));
                    }

                }else if(li.get("type").equals("DEP")){
                    if(dids.length() == 0){
                        dids.append(li.get("id"));
                    }else{
                        dids.append("," + li.get("id"));
                    }
                }
            }
        }

//        System.err.println(oids);
//        System.err.println(dids);
        ((Map)data.get(0)).put("oid",oids.toString());
        ((Map)data.get(0)).put("did",dids.toString());
//        Object oid = org.stream().filter(v ->
//            ((Map)v).get("type").equals("ROLE")
//        ).collect(Collectors.);
//        System.err.println(oid);
//        org.forEach(v->{
//            Map li = ((Map)v);
//            if(li.get("type").equals("ROLE")){
//                if(oids == null){
//                    oids += li.get("oid");
//                }
//                System.err.println("oid");
//                System.err.println(li.get("oid"));
//            }else if(li.get("type").equals("USER")){
//                System.err.println("did");
//                System.err.println(li.get("oid"));
//            }
//        });
        return data;
    }
    /**
     * 新建用户
     * */
    public Object newUser(){
        Map info = Json.parse($post.get("info").toString());
        ObjectId.get();
        String uid = ObjectId.get().toString();
//        Long uid = getSnowflakeIDWorker.nextId();

        String pwd = info.get("password").toString();
//        String pwd = DigestUtils.md5DigestAsHex(info.get("password").toString().getBytes());
//        System.err.println(info.get("department"));
//        System.err.println(info.get("oid"));
        Arr org = a();
        Arr dep = Json.parse(info.get("department").toString());
        Arr rule = Json.parse(info.get("oid").toString());
        for(Object i: dep){
            org.add(o("id",i,"type","DEP"));
        }
        for(Object i: rule){
            org.add(o("id",i,"type","ROLE"));
        }
        // 是否为简易版创建
        Document newUser = null;
        if(info.get("isEasy").equals("0") ){
            newUser = o(
                    "id",String.valueOf(uid),
                    "baned",0,
                    "new_user",1,
                    "su",0,
                    "password",pwd,
                    "phone",info.get("phone"),
                    "true_name",info.get("true_name"),
                    "username",info.get("username"),
                    "email",null,
                    "letter",null,
                    "org_info",null,
                    "private_key",null,
                    "public_key",null,
                    "org_detail",null,
                    "sex",info.get("sex"),
                    "acc_code",info.get("username"),
                    "add_time",new Date(),
                    "avatar","face.jpg",
                    "cloud_username",info.get("username"),
                    "cloud_password","qwer!@34",
                    "user_code",info.get("user_code"),
                    "orgs",org
            ).toBson();
        }else{
            newUser = o(
                    "id",String.valueOf(uid),
                    "su",0,
                    "password",pwd,
                    "true_name",info.get("true_name"),
                    "username",info.get("username"),
                    "phone",info.get("phone"),
                    "orgs",org
            ).toBson();
        }

        db.getCollection("user")
                .insertOne(newUser);
//        System.err.println(newUser);
        return null;
    }
    /**
     * 删除用户
     * */
    public Object delUser(){
        db.getCollection("user")
                .deleteOne(o(
                        "id", $post.s("id")
                ).toBson());
        return null;
    }
    /**
     * 批量处理
     * */
    public Object CheckoutOperation(){

        Arr ls = Json.parse($get.s("id"));
        if($get.s("type").equals("del")){
            // 删除用户
            db.getCollection("org").deleteMany(o(
                    "id", o("$in",ls)
            ).toBson());


        }else if($get.s("type").equals("edit")){
            Arr data = db.getCollection("restPwd").find(o().toBson()).limit(1).into(a());
            String pwd = ((Map)data.get(0)).get("password").toString();
            db.getCollection("user")
                    .updateMany(
                            o("id", o("$in",ls)).toBson(), o("$set",o("password",pwd)).toBson()
                    );
        }
        return null;
    }
    /**
     * 用户编辑
     * */
    public Object editUser(){
        Map info = Json.parse($post.get("info").toString());
        Arr org = a();
        Arr dep = Json.parse(info.get("department").toString());
        Arr rule = Json.parse(info.get("oid").toString());
        for(Object i: dep){
            org.add(o("id",i,"type","DEP"));
        }
        for(Object i: rule){
            org.add(o("id",i,"type","ROLE"));
        }
        // 删除orgs
        db.getCollection("user")
                .updateMany(
                        o("id", info.get("id")).toBson(), o("$set",o("orgs",null)).toBson()
                );
        // 写入orgs
        db.getCollection("user")
                .updateMany(
                        o("id", info.get("id")).toBson(), o("$set",o(
                                "phone",info.get("phone"),
                                "true_name",info.get("true_name"),
                                "username",info.get("username"),
                                "sex",info.get("sex"),
                                "user_code",info.get("user_code"),
                                "orgs",org
                        )).toBson()
                );

        return null;
    }
    /**
     * 用户搜索
     * */
    public Object searchUser(){
        Obj info = Json.parse($post.s("info","{}"));
        int page = $post.i("pre",1);
//        System.err.println();
        if(page != 1){
            page = (page - 1)  * 10;
        }else{
            page = 0;
        }
        return searchAndExport(info,page,"search");
//        System.err.println(info);
//        Obj codition = o("$match",o());
//        Arr sorgs = a();
//        if(info.get("department") != null){
//            if(((Arr)Json.parse(info.get("department").toString())).size() != 0){
////            System.err.println((Arr)Json.parse(info.get("department").toString()));
//                sorgs.addAll((Arr)Json.parse(info.get("department").toString()));
////            System.err.println(222);
//            }
//        }
//        if(info.get("role") != null){
//            if(((Arr) Json.parse(info.get("role").toString())).size() != 0){
////            System.err.println((Arr)Json.parse(info.get("role").toString()));
//                sorgs.addAll((Arr)Json.parse(info.get("role").toString()));
////            System.err.println(222);
//            }
//        }
//
////        部门与角色
//        if(sorgs.size() != 0){
//            codition.put("$match",o("orgs",o("$elemMatch",o("id",o("$in",sorgs)))));
//        }
//        // 其他选项
//        Obj other = o();
//        if(info.get("id") != null){
//            if(!info.get("id").toString().equals("")){
//                other.put("id",o("$regex",info.get("id").toString()));
//            }
//        }
//        if(info.get("userName") != null){
//            if( !info.get("userName").toString().equals("")){
//                other.put("username",o("$regex",info.get("userName").toString()));
//            }
//        }
//        if(info.get("name") != null){
//            if(!info.get("name").toString().equals("")){
//                other.put("true_name",o("$regex",info.get("name").toString()));
//            }
//        }
//        if(info.get("phone") != null){
//            if(!info.get("phone") .toString().equals("")){
//                other.put("phone",o("$regex",info.get("phone").toString()));
//            }
//        }
//
////        if(!info.get("sex") .toString().equals("")){
////            other.put("sex",o("$regex",info.get("sex").toString()));
////        }
////        if(!info.get("user_code") .toString().equals("")){
////            other.put("user_code",o("$regex",info.get("user_code").toString()));
////        }
////        System.err.println(other);
//        if (other.size() != 0){
//            codition.put("$match",o("$and",a(other)));
//        }
////        System.err.println(codition);
////        System.err.println($post);
//        int page = $post.i("pre",1);
////        System.err.println();
//        if(page != 1){
//            page = (page - 1)  * 10;
//        }else{
//            page = 0;
//        }
//        Arr users = db.getCollection("user").aggregate(
//                a(
//                        codition,
//                        o("$project",o("id","$id","username","$username","phone","$phone","true_name","$true_name","orgs","$orgs")),
//                        o("$skip",page),
//                        o("$limit",10)
//                ).toBson()
//        ).into(a());
//        Arr count = db.getCollection("user").aggregate(
//                a(
//                        codition,
//                        o("$project",o("id","$id")),
//                        o("$count","count")
//                ).toBson()
//        ).into(a());
//        // 获取所有用户的orgs
//        Arr orgs = a();
//        for(Object i : users){
//            Map data = (Map)i;
////            System.err.println(data);
//            if(data.get("orgs") != null){
//                ArrayList org = (ArrayList)data.get("orgs");
//                for(Object t : org){
//                    orgs.add(((Map)t).get("id"));
//                }
//            }
//
//        }
////        System.err.println(orgs);
//        int totalPage = count.size() == 0 ? 0 : Integer.parseInt(count.o(0).s("count") );
//        Arr allUser = userOparetion(users,orgs);
////        System.err.println(o("data",allUser,"totalRow",o("count",totalPage)).toBson());
//        return o("data",allUser,"totalRow",o("count",totalPage));
//        return null;
    }
    /**
     * 搜索与导出
     * */
    public Obj searchAndExport(Obj info,int page,String type){
//        Obj info = Json.parse($post.s("info","{}"));

//        System.err.println(info);
        Obj codition = o("$match",o());
        Arr sorgs = a();
        if(info.get("department") != null){
            if(((Arr)Json.parse(info.get("department").toString())).size() != 0){

                sorgs.addAll((Arr)Json.parse(info.get("department").toString()));

            }
        }
        if(info.get("role") != null){
            if(((Arr) Json.parse(info.get("role").toString())).size() != 0){

                sorgs.addAll((Arr)Json.parse(info.get("role").toString()));

            }
        }

//        部门与角色
        if(sorgs.size() != 0){
            codition.put("$match",o("orgs",o("$elemMatch",
                    o("$and",a(
                            o("id",o("$in",sorgs)),
                            o("type",o("$in",a(
                                    "DEP",
                                    "ROLE"
                            )))
                    )))

            ));
        }
//        System.out.println(codition);
        // 其他选项
        Obj other = o();
        if(info.get("id") != null){
            if(!info.get("id").toString().equals("")){
                other.put("id",o("$regex",info.get("id").toString()));
            }
        }
        if(info.get("userName") != null){
            if( !info.get("userName").toString().equals("")){
                other.put("username",o("$regex",info.get("userName").toString()));
            }
        }
        if(info.get("name") != null){
            if(!info.get("name").toString().equals("")){
                other.put("true_name",o("$regex",info.get("name").toString()));
            }
        }
        if(info.get("phone") != null){
            if(!info.get("phone") .toString().equals("")){
                other.put("phone",o("$regex",info.get("phone").toString()));
            }
        }

//        if(!info.get("sex") .toString().equals("")){
//            other.put("sex",o("$regex",info.get("sex").toString()));
//        }
//        if(!info.get("user_code") .toString().equals("")){
//            other.put("user_code",o("$regex",info.get("user_code").toString()));
//        }
//        System.err.println(other);
        if (other.size() != 0){
            codition.put("$match",o("$and",a(other)));
        }

        Arr users = new Arr();
        Arr count = new Arr();
        if(type.equals("search")){
            users = db.getCollection("user").aggregate(
                    a(
                            codition,
                            o("$project",o("id","$id","username","$username","phone","$phone","true_name","$true_name","orgs","$orgs")),
                            o("$skip",page),
                            o("$limit",10)
                    ).toBson()
            ).into(a());
            count = db.getCollection("user").aggregate(
                    a(
                            codition,
                            o("$project",o("id","$id")),
                            o("$count","count")
                    ).toBson()
            ).into(a());
        }else{
            users = db.getCollection("user").aggregate(
                    a(
                            codition,
                            o("$project",o("id","$id","username","$username","phone","$phone","true_name","$true_name","orgs","$orgs"))

                    ).toBson()
            ).into(a());
            count = db.getCollection("user").aggregate(
                    a(
                            codition,
                            o("$project",o("id","$id")),
                            o("$count","count")
                    ).toBson()
            ).into(a());
        }
        // 获取所有用户的orgs
        Arr orgs = a();
        for(Object i : users){
            Map data = (Map)i;

            if(data.get("orgs") != null){
                ArrayList org = (ArrayList)data.get("orgs");
                for(Object t : org){
                    orgs.add(((Map)t).get("id"));
                }
            }

        }

        int totalPage = count.size() == 0 ? 0 : Integer.parseInt(count.o(0).s("count") );
        Arr allUser = userOparetion(users,orgs);

        return o("data",allUser,"totalRow",o("count",totalPage));

    }
    /**
     * 处理用户数据 用于写入用户所在部门及角色
     * */
    private Arr userOparetion(Arr users,Arr orgs){

        Arr userInOrg = db.getCollection("dep").aggregate(
                a(
                        o("$match",o("id",o("$in",orgs))),
                        o("$project",o("_id",0,"id","$id","name","$name"))
                ).toBson()
        ).into(a());
        Arr userInRole = db.getCollection("role").aggregate(
                a(
                        o("$match",o("id",o("$in",orgs))),
                        o("$project",o("_id",0,"id","$id","name","$name"))
                ).toBson()
        ).into(a());
//        System.err.println(userInOrg.toBson());
        // 匹配用户
        for(Object i : users){
            Map data = (Map)i;
            ArrayList org = (ArrayList)data.get("orgs");
            StringBuilder name = new StringBuilder();
            StringBuilder d_name = new StringBuilder();
            if(org != null){
                for(Object t : org){
                    // 部门角色 赋值给用户
                    for(Object v : userInOrg){
                        if(((Map)t).get("type").equals("DEP")){
                            if(((Map)t).get("id").equals(((Map)v).get("id"))){
//                            System.err.println(((Map)v).get("name"));
                                if(d_name.length() == 0){
                                    d_name.append(((Map)v).get("name"));
                                }else{
                                    d_name.append("," + ((Map)v).get("name"));
                                }
                            }
                        }
                    }
                    for(Object v : userInRole){
                        if(((Map)t).get("type").equals("ROLE")){
                            if(((Map)t).get("id").equals(((Map)v).get("id"))){
//                            System.err.println(((Map)v).get("name"));
                                if(name.length() == 0){
                                    name.append(((Map)v).get("name"));
                                }else{
                                    name.append("," + ((Map)v).get("name"));
                                }
                            }
                        }
                    }
                }

            }
            // 写入用户
            data.put("name",name.toString());
            data.put("d_name",d_name.toString());
        }
//        System.err.println(users.toBson());
        return users;
    }
    /**
     * 以下为用户详情
     * */
    public Object userInfo(){
        Arr UserInfo = db.getCollection("user").aggregate(
                a(
                        o("$match",o("id",Auth.getUid())),
                        o("$project",o("id","$id","username","$username","user_code","$user_code","sex","$sex","phone","$phone","true_name","$true_name","orgs","$orgs"))
                ).toBson()
        ).into(a());
        if(UserInfo.size() <= 0){
            throw new RestException("无此用户");
        }
        Map data = (Map)UserInfo.get(0);
//        System.err.println();
        Arr role = a();
        Arr dep = a();
        if(data.get("orgs") != null){
//            System.err.println(data.get("orgs"));
            for(Object t : ((ArrayList)data.get("orgs"))){
//                System.err.println(t);
                Map item = (Map)t;
                if(item.get("type").equals("ROLE")){
                    role.add(item.get("id"));
                }else if(item.get("type").equals("DEP")){
                    dep.add(item.get("id"));
                }
            }
        }
        if(role.size() != 0){
            Arr roles = db.getCollection("role").aggregate(a(
                    o("$match",o("id",o("$in",role))),
                    o("$project",o("name","$name"))
            ).toBson()).into(a());
            data.put("role",roles);
        }
        if(dep.size() != 0){
            Arr deps = db.getCollection("role").aggregate(a(
                    o("$match",o("id",o("$in",dep))),
                    o("$project",o("name","$name"))
            ).toBson()).into(a());
            data.put("dep",dep);
        }
//        System.err.println(roles);

        return data;
    }
    /**
     * 用户编辑保存
     * */
    public Object editSave(){
        Map info = Json.parse($post.s("info"));
        Obj data = o();
        if(info.get("phone") != null){
            data.put("phone",info.get("phone"));
        }
        if(info.get("password") != null){
            data.put("password",info.get("password"));
        }
//        System.err.println(data);
        db.getCollection("user")
                .updateMany(
                        o("id", Auth.getUid()).toBson(), o("$set",data).toBson()
                );
        return null;
    }
    /**
     * 导出
     * */
    public Object export(){
        File temp = new File(tempDir, StrUtil.uuid() + ".xlsx");
        Obj info = Json.parse($post.s("info","{}"));
//        searchAndExport(info,0,"export");
//        return new MultipartFile(".data", temp, true);
//        ExcelWriter writer = ExcelUtil.getWriter(temp);
        ExcelWriter writer = new ExcelWriter(temp);
        String[] columns = {"用户名", "手机号", "真实姓名", "部门"};
        for (int i = 0; i < columns.length; i++) {
            writer.writeCellValue(i, 0, columns[i]);
        }

        Obj userMap = searchAndExport(info,0,"export");
        List<Document> userList = (List<Document>) userMap.get("data");
        int row = 1;
        int max = 0;
        for (Document obj : userList) {
            writer.writeCellValue(0, row, obj.get("username").toString());
            writer.writeCellValue(1, row, obj.get("phone").toString());
            writer.writeCellValue(2, row, obj.get("true_name").toString());

            String deptName = obj.get("d_name").toString();
            if(null != deptName){
                writer.writeCellValue(3, row, deptName);
            }
            String role = obj.get("name").toString();
            if(null != role){
                List<String> roleList = Arrays.asList(role.split(","));
                if(roleList == null){
                    continue;
                }
                for (int i = 0; i < roleList.size(); i++) {
                    writer.writeCellValue(i+4, row, roleList.get(i));
                }
                max = Math.max(roleList.size(), max);
            }

//            Arr arr = Json.parse(obj.s("org_detail","[]"));
//            for (int i = 0; i < arr.size(); i++) {
//                writer.writeCellValue(i+3, row, arr.o(i).s("name"));
//            }
            row++;
        }

        for (int i = 0; i < max; i++) {
            writer.writeCellValue(4+i, 0, "角色" + (i + 1));
        }
        for (int i = 0; i < 20; i++) {
            writer.setColumnWidth(i, 30);
        }
        writer.flush();
        writer.close();

        return new MultipartFile("data.xlsx", temp, true);
    }

    /**
     * 导入模板
     *
     * */
    public Object importTemp(){
        File temp = null;
        ExcelWriter writer = null;
        try {
            temp = new File(tempDir, StrUtil.uuid() + ".xlsx");
            writer =  new ExcelWriter(temp);
            String[] columns = {"用户名", "手机号", "真实姓名","部门/角色1","部门/角色2"};
            for (int i = 0; i < columns.length; i++) {
                writer.writeCellValue(i, 0, columns[i]);
            }
            writer.writeCellValue(0, 1, "zhangsan");
            writer.writeCellValue(1, 1, "15566667777");
            writer.writeCellValue(2, 1, "张三");
            writer.writeCellValue(3, 1, "基础角色");
            writer.writeCellValue(4, 1, "惠州农村商业银行-信息科技部(上级主管)");
            for (int i = 0; i < 20; i++) {
                writer.setColumnWidth(i, 30);
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            if(null != temp){
                temp.delete();
            }
            writer.flush();
            writer.close();
        }
        return new MultipartFile("模板.xlsx", temp, true);
    }

    /**
     * 导入
     * */
    public void importData(MultipartFile file,Boolean toUpdate){
        File temp = null;
        try {
            temp = File.createTempFile("123", "");

//            System.out.println(file.fileName);
            file.transferTo(temp);
//            System.out.println($post.b("toUpdate"));
            uploadUser(temp,$post.b("toUpdate"));
//            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (temp != null) {
                temp.delete();
            }
        }

    }
    /**
     * 导入
     * @param file
     */
    private void uploadUser(File file, boolean toUpdate){
//        File file = new File("d://用户导入模板.xlsx");
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            XSSFWorkbook workbook = new XSSFWorkbook(is);

            //得到第一个sheet
            Sheet sheet = workbook.getSheetAt(0);
            //得到Excel的行数
            int totalRows = sheet.getPhysicalNumberOfRows();
            int totalCells=0;
            //得到Excel的列数
            if (totalRows >= 1 && sheet.getRow(0) != null){
                totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
            Date nowDate = new Date();
            Map<String, String> roleMap = new HashMap<>();
//            List<Obj> list = sqlManager.execute(new SQLReady("select id,name from t_org where type='ROLE'"), Obj.class);
            Arr list = db.getCollection("role").find().into(a());
            for (Object obj : list) {
                Obj doc = ooo(obj);
                roleMap.put(doc.s("name"), doc.s("id"));
            }

//            循环Excel的行
            for(int r=1;r<totalRows;r++){
                Row row = sheet.getRow(r);
                if (row == null){
                    continue;
                }
                String accCode = "";
                String phone = "";
                String trueName = "";
                String passWord = "";
                Obj deps = o();
                List<String> roles = new ArrayList<>();
                JSONArray all = new JSONArray();

                //取出列单元格中的信息
                for(int i=0;i<totalCells;i++){
                    Cell cellValue = row.getCell(i);

                    if(null == cellValue){
                        continue;
                    }

                    if(i == 0){

                        accCode = cellValue.getStringCellValue();
//                        System.out.println(i);
                    }
                    /*else if(i == 1){
                        //设置单元格类型
                        cellValue.setCellType(CellType.STRING);
                        passWord = cellValue.getStringCellValue();

                        passWord = passWord.equals("") ? DigestUtils.md5DigestAsHex(accCode.getBytes()) : DigestUtils.md5DigestAsHex(passWord.getBytes());
                    }*/
                    else if(i == 1){
                        //设置单元格类型
                        cellValue.setCellType(CellType.STRING);
                        phone = cellValue.getStringCellValue();
                    }else if(i == 2){
                        trueName = cellValue.getStringCellValue();

                    }else{
//                        System.err.println(22222);
                        String [] valueArr = cellValue.getStringCellValue().split("\\(");
//                        System.err.println(valueArr.length);
                        if(valueArr.length>1){   //左括号的转义
                            String dp = valueArr[0];
                            String rp = valueArr[1].substring(0,valueArr[1].length()-1);

                            if(dp.contains("-")){
                                List<String> cellList = Arrays.asList(cellValue.getStringCellValue().split("-"));
                                List<Document> tree = new dep().list().list();

                                int m= 0;
                                for (String s : cellList) {
                                    m++;
                                    String a[]=s.split("\\(");//左括号的转义
//                                    List<Obj> obj = aa(tree, a[0]);
//                                    System.err.println(s);
                                    List<Document> obj = new ArrayList<>();
                                    String id = null;
                                    for (Document obj1 : tree) {
                                        String children = (String) obj1.get("name");
//                                        System.out.println(obj1.get("name"));
                                        if(children.equals(a[0])){
                                            id = obj1.get("id").toString();
//                                            System.err.println(id);
                                            List<Obj> child = (List<Obj>) obj1.get("children");
                                            if(null == child){
                                                obj = new ArrayList<>();
                                                obj.add(obj1);
                                            }else{
                                                obj = (List<Document>) obj1.get("children");
                                            }
                                            break;
                                        }
                                    }
                                    if(null == obj){
                                        continue;
                                    }
                                    if(cellList.size() == m){
                                        String type = a[1] == null ? "" : a[1].substring(0,a[1].length()-1);
                                        deps.put(id + "-" + type, a[0]);
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("id",id);
                                        jsonObject.put("name",cellValue.getStringCellValue());
                                        jsonObject.put("type","DEP");
                                        all.add(jsonObject);
//                                        deps.put(String.valueOf(obj.get(0).get("id")) + "-" + type, a[0]);
                                    }
//                                    if(obj.size() ==1){
//                                        String type = a[1] == null ? "" : a[1].substring(0,a[1].length()-1);
//                                        deps.put(String.valueOf(obj.get(0).get("id")) + "-" + type, a[0]);
//                                    }
//                                roles.put("",a[0]);
                                    tree = obj;
                                }
                            }else{
                                List<Obj> tree = new dep().list().list();
                                String id = getDeptId(tree, dp);
                                if(null == id){
                                    continue;
                                }
                                deps.put(String.valueOf(id) + "-" + rp, dp);
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id",id);
                                jsonObject.put("name",cellValue.getStringCellValue());
                                jsonObject.put("type","DEP");
                                all.add(jsonObject);
                            }
                        }else{  // 角色
                            roles.add(valueArr[0]);

//                            List<Obj> roleList = sqlManager.execute(new SQLReady("select * from t_org where name =? and type=?", valueArr[0], "ROLE"), Obj.class);
                            Arr roleList = db.getCollection("role").find(
                                    o(
                                        "name",valueArr[0]
                                    ).toBson()
                            ).into(a());
                            if(roleList.size()>0){
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id",((Document)roleList.get(0)).get("id"));
                                jsonObject.put("name",cellValue.getStringCellValue());
                                jsonObject.put("type","ROLE");
                                all.add(jsonObject);
                            }
                        }
//                        System.out.println(accCode);
                        /*if(cellValue.getStringCellValue().contains("-")){
                            List<String> cellList = Arrays.asList(cellValue.getStringCellValue().split("-"));
                            List<Obj> tree = (List<Obj>) dep.list();
                            for (String s : cellList) {
                                String a[]=s.split("\\(");//左括号的转义
                                List<Obj> obj = aa(tree, a[0]);
                                if(null == obj){
                                    continue;
                                }
                                if(obj.size() ==1){
                                    String type = a[1] == null ? "" : a[1].substring(0,a[1].length()-1);
                                    deps.put(String.valueOf(obj.get(0).get("id")), type + "-" + a[0]);
                                }
//                                roles.put("",a[0]);
                                tree = obj;
                            }
                        }*/
                    }
                }

                String uid = null;
                if(StrUtil.equals("", accCode)){
                    continue;
                }
//                List<Obj> userList = sqlManager.execute(new SQLReady("select * from t_user where acc_code =?", accCode), Obj.class);
                Arr userList = db.getCollection("user").find(
                        o(
                                "username",accCode
                        ).toBson()
                ).into(a());
//
//                /*StringBuffer info = new StringBuffer();
//                int n = 0;
//                for (Object o : all) {
//                    n++;
//                    JSONObject js = (JSONObject) o;
//                    info.append(js.get("name"));
//                    if(all.size()-n != 0){
//                        info.append("/");
//                    }
//                }*/

                if(userList.size()>0){
                    if(toUpdate){

                        uid = ((Document)userList.get(0)).get("id").toString();
                        db.getCollection("user")
                                .updateMany(
                                        o("username", accCode).toBson(), o("$set",o(
                                                "phone",phone,
                                                "true_name",trueName,
                                                "username",accCode,
                                                "sex","2",
                                                "user_code",accCode
                                        )).toBson()
                                );

//                        sqlManager.executeUpdate(new SQLReady("update t_user set add_time=?,phone=?,true_name = ? where acc_code = ?", nowDate,phone, trueName,accCode));
                    }
                }else{

                    uid = ObjectId.get().toString();

                    /**
                     * 老板要求增加的用户自定义密码
                     * */
//                    Arr data = db.getCollection("restPwd").find(o().toBson()).limit(1).into(a());
                    String pwd  = "c81e728d9d4c2f636f067f89cc14862c";
//                    if(data.size() != 0){
//                        pwd = ((Map)data.get(0)).get("password").toString();
//                    }
                    // 寫入用户
                    Document newUser = o(
                            "id",String.valueOf(uid),
                            "su",0,
                            "password",pwd,
                            "true_name",trueName,
                            "username",accCode,
                            "phone",phone
                    ).toBson();
                    db.getCollection("user")
                            .insertOne(newUser);
//                    System.err.println(newUser);
//                    sqlManager.executeUpdate(new SQLReady("insert into t_user(id,acc_code,add_time,phone,password,username,true_name,baned,new_user,su) values (?,?,?,?,?,?,?,?,?,?)",
//                            uid, accCode, nowDate,phone, DigestUtils.md5DigestAsHex(pwd.getBytes()), accCode, trueName,"0","1","0"));

//                    sqlManager.executeUpdate(new SQLReady("insert into t_user(id,acc_code,add_time,phone,password,username,true_name,baned,new_user,su) values (?,?,?,?,?,?,?,?,?,?)",
//                            uid, accCode, nowDate,phone, DigestUtils.md5DigestAsHex(accCode.getBytes()), accCode, trueName,"0","1","0"));

                }
                Arr org = a();
                Arr dep = a();
                Arr rule = a();
                for(Object i: dep){
                    org.add(o("id",i,"type","DEP"));
                }
                for(Object i: rule){
                    org.add(o("id",i,"type","ROLE"));
                }
                for (Map.Entry<String, Object> m : deps.entrySet()) {
                    String tp = m.getKey();
                    String[] tpArr = tp.split("-");
                    String type = "";

                    switch (tpArr[1]){
                        case "用户":
                            type = "DEP";
                            break;
                        case "上级主管":
                            type = "TOP_MANAGER0";
                            break;
                        case "上级分管":
                            type = "TOP_MANAGER1";
                            break;
                    }
                    if(tpArr[0] == null){
                        throw new RestException("无此部门");
                    }
                    org.add(o("id",tpArr[0],"type",type));
//                        boolean dep = sqlManager.execute(new SQLReady("select * from t_user_dep where did =? and uid=? and type=?",tpArr[0], uid, type), Obj.class).size()>0;
//                        if(!dep){
//                            sqlManager.executeUpdate(new SQLReady("insert into t_user_dep(did,uid,type) values (?,?,?)", tpArr[0], uid, type));
//                        }
                }
                // 角色
                for(String role :roles){
                    String roleId = roleMap.get(role);
                    if(null == roleId){
                        continue;
                    }
                    if(roleId == null){
                        throw new RestException("无此部门");
                    }
                    org.add(o("id",roleId,"type","ROLE"));
//                    System.out.println(roleId);
//                        boolean role1 = sqlManager.execute(new SQLReady("select * from t_org where name =? and type=?",role, "ROLE"), Obj.class).size()>0;
//                        if(role1){
//                            boolean org = sqlManager.execute(new SQLReady("select * from t_user_org where oid =? and uid=?",roleId, uid), Obj.class).size()>0;
//                            if(!org){
//                                sqlManager.executeUpdate(new SQLReady("insert into t_user_org(oid,uid) values (?,?)", roleId, uid));
//                            }
//                        }
                }

                if(userList.size()>0){
                    System.err.println(toUpdate);
                    if(toUpdate){
                        System.err.println(org);
                        db.getCollection("user")
                                .updateMany(
                                        o("id", uid).toBson(), o("$set",o(
                                                "orgs",org
                                        )).toBson()
                                );

                    }

                }else{
                    db.getCollection("user")
                            .updateMany(
                                    o("id", uid).toBson(), o("$set",o(
                                           "orgs",org
                                    )).toBson()
                            );
                }


            }
//
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 更改用户排序
     * */
    public Object rowAdjust(){
        String type = $get.s("type","up");
        if(type.equals("up")){

        }else if(type.equals("down")){

        }
        return null;

    }
    /**
     * 得到部门id
     * @param list
     * @param name
     * @return
     */
    private String getDeptId(List<Obj> list, String name){
        String id = null;
        for (Obj obj1 : list) {
            String children = (String) obj1.get("name");
            if(children.equals(name)){
                id = obj1.get("id").toString();
                break;
            }
        }
        return id;
    }
}
